﻿
using System;
using System.Linq;
using ABC.Core.Configuration;
using ABC.Core.Providers;

namespace ABC.Business.Models
{
    public class VkModel
    {
        private const string ApiUrl = "http://api.vkontakte.ru/api.php";

        private static readonly IApplicationSettingsProvider ApplicationSettingsProvider = IoC.Resolve<IApplicationSettingsProvider>();

        public static string GetLastSeen(string iUserID)
        {
            var sRandom = "random=" + GetRandom(int.MaxValue);
            return ApiUrl + "?api_id=" + ApplicationSettingsProvider.VkApplicationId
                + "&method=users.get"
                + "&v=3.0"
                + "&" + sRandom
                + "&fields=last_seen,sex"
                + "&uid=" + iUserID
                + "&sig=" + GenerateSig(new[] 
                    { "api_id=" + ApplicationSettingsProvider.VkApplicationId, "v=3.0", "method=users.get", "fields=last_seen,sex",
                        "uid=" + iUserID, sRandom
                    });

        }
        private static int GetRandom(int maxValue)
        {
            var r = new Random();
            return r.Next(maxValue);
        }
        public static string GenerateSig(string[] aParams)
        {
            Array.Sort(aParams);
            var s = aParams.Aggregate("", (current, t) => current + t);
            s += ApplicationSettingsProvider.VkSecretKey;
            return GetMd5Hash(s);
        }

        public static string GetMd5Hash(string input)
        {
            var x = new System.Security.Cryptography.MD5CryptoServiceProvider();
            var bs = System.Text.Encoding.UTF8.GetBytes(input);
            bs = x.ComputeHash(bs);
            var s = new System.Text.StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2").ToLower());
            }
            string password = s.ToString();
            return password;
        }
    }
}
